/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.rsa.management.key;

import com.asialjim.encommunicate.base.rsa.key.RSAClientKey;
import com.asialjim.encommunicate.base.rsa.key.RSAServerKey;
import com.asialjim.encommunicate.rsa.management.pojo.AppEnDecryptInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * RSA 密钥对查找
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/27, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
@Component
public class RSAKeyLookUpComponent {
    @Autowired private List<RSAKeyRepository> repositories;
    @Autowired private RSAKeyMemoryRepository memoryRepository;

    public Set<RSAClientKey> clientKeys(){
        return infos().stream()
                .map(item -> RSAClientKey.builder().priKey(item.getClientPriKey()).pubKey(item.getClientPubKey()).build())
                .collect(Collectors.toSet());
    }

    public Set<RSAServerKey> serverKeys(){
        return infos().stream()
                .map(item -> RSAServerKey.builder().priKey(item.getServerPriKey()).pubKey(item.getServerPubKey()).build())
                .collect(Collectors.toSet());
    }

    public Set<AppEnDecryptInfo> infos(){
        Set<AppEnDecryptInfo> res = new HashSet<>();
        repositories.stream().map(RSAKeyRepository::infos).forEach(res::addAll);
        return res;
    }

    public Set<AppEnDecryptInfo> modify(AppEnDecryptInfo body) {
        repositories.parallelStream().forEach(rep -> rep.modify(body));
        return infos();
    }

    /**
     * 获取服务端密钥对，当获取不到时，返回空值
     *
     * @param appid {@link String appid}
     * @return {@link RSAServerKey 服务端密钥对}
     * @since 2023/2/27
     */
    public RSAServerKey serverKeyNullable(String appid) {
        try {
            return serverKeyThrowable(appid);
        } catch (Throwable t) {
            return null;
        }
    }

    /**
     * 获取客户端密钥对，当获取不到时，返回空值
     *
     * @param appid {@link String appid}
     * @return {@link RSAClientKey 客户端密钥对}
     * @since 2023/2/27
     */
    public RSAClientKey clientKeyNullable(String appid) {
        try {
            return clientKeyThrowable(appid);
        } catch (Throwable t) {
            return null;
        }
    }

    /**
     * 获取服务端密钥对, 当获取不到时，抛出错误
     *
     * @param appid {@link String appid}
     * @return {@link RSAServerKey 服务端密钥对}
     * @since 2023/2/27
     */
    public RSAServerKey serverKeyThrowable(String appid) {
        RSAServerKey rsaServerKey = memoryRepository.serverKey(appid);
        if (Objects.nonNull(rsaServerKey))
            return rsaServerKey;

        for (RSAKeyRepository repository : repositories) {
            rsaServerKey = repository.serverKey(appid);
            if (Objects.nonNull(rsaServerKey))
                break;
        }

        if (Objects.isNull(rsaServerKey))
            throw new IllegalStateException("应用：" + appid + " 没有配置密钥对");

        return rsaServerKey;
    }

    /**
     * 获取客户端密钥对, 当获取不到时，抛出错误
     *
     * @param appid {@link String appid}
     * @return {@link RSAClientKey 客户端密钥对}
     * @since 2023/2/27
     */
    public RSAClientKey clientKeyThrowable(String appid) {
        RSAClientKey rsaClientKey = memoryRepository.clientKey(appid);
        if (Objects.nonNull(rsaClientKey))
            return rsaClientKey;

        for (RSAKeyRepository repository : repositories) {
            rsaClientKey = repository.clientKey(appid);
            if (Objects.isNull(rsaClientKey))
                break;
        }

        if (Objects.isNull(rsaClientKey))
            throw new IllegalStateException("应用：" + appid + " 没有配置密钥对");

        return rsaClientKey;
    }
}